package com.ruoyi.central.controller;

import java.util.List;

import com.ruoyi.central.common.domain.TopCentralProductTypeUtils;
import com.ruoyi.central.domain.TopCentralProductType;
import com.ruoyi.central.enums.ProductMaterialType;
import com.ruoyi.central.service.ITopCentralProductTypeService;
import com.ruoyi.common.core.domain.Tree;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.service.ServiceUtils;
import com.ruoyi.common.validation.group.InsertGroup;
import com.ruoyi.common.validation.group.UpdateGroup;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import com.ruoyi.common.utils.bean.SelectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.ModelMap;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.central.domain.TopCentralProduct;
import com.ruoyi.central.service.ITopCentralProductService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import org.springframework.validation.annotation.Validated;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.validation.group.UpdateBatchGroup;
import com.ruoyi.common.core.domain.StateVo;
import java.util.Collection;
import java.util.Map;
import java.util.Set;

/**
 * 产品Controller
 * 
 * @author SunLuQuan
 * @date 2022-06-22
 */
@Controller
@RequestMapping("/central/centralProduct")
public class TopCentralProductController extends BaseController
{
    private String prefix = "central/centralProduct";

    @Autowired
    private ITopCentralProductService topCentralProductService;

    @Autowired
    private ITopCentralProductTypeService productTypeService;

    @RequiresPermissions("central:centralProduct:view")
    @GetMapping()
    public String centralProduct()
    {
        return prefix + "/centralProduct";
    }

    /**
     * 根据产品批次号查找当前批次号的根产品
     * 1.获取所有为当前批次号的 物料集合
     * 2.获取所有 产品类型为产品的 产品类型集合
     * 3.查找 物料集合 与 产品类型集合 中是否有一致的产品类型
     * @param batchNo 产品批次好
     * @param materialType 过滤的类型
     * @return
     */
    @GetMapping("/findRoot/{batchNo}")
    @ResponseBody
    public AjaxResult findRoot(@PathVariable("batchNo") String batchNo,@RequestParam(name = "materialType",required = false,defaultValue = "1") ProductMaterialType materialType){

        TopCentralProduct product = topCentralProductService.selectUsableByBatchNo(batchNo);

        Map<Integer, Tree<TopCentralProductType>> treeMap = productTypeService.productTypeTreeAll();

        Tree<TopCentralProductType> productTypeTree = treeMap.get(product.getTypeId());

        if(StringUtils.isNotNull(productTypeTree)){
            Set<TopCentralProductType> productTypes = TopCentralProductTypeUtils.filterProductTypeList(productTypeTree,materialType);
            product.setProductTypes(productTypes);
        }

        return AjaxResult.success(product);
    }

    /**
     * 查询产品列表
     */
    @RequiresPermissions("central:centralProduct:list")
    @GetMapping("/list")
    @ResponseBody
    public TableDataInfo list(TopCentralProduct topCentralProduct)
    {
        startPage();
        List<TopCentralProduct> list = topCentralProductService.selectList(topCentralProduct);

        ServiceUtils.complete(list,productTypeService,(productTypeMap, product) -> product.setProductType(productTypeMap.get(product.getTypeId())));

        return getDataTable(list);
    }

    /**
     * 查询简单的产品列表 用于select选择器
     */
    @GetMapping("/simpleList")
    @ResponseBody
    public AjaxResult simpleList(TopCentralProduct topCentralProduct){

        Collection<TopCentralProduct> topCentralProductList = topCentralProductService.selectAllMap().values();

        return AjaxResult.success(SelectUtils.buildSelectList(topCentralProductList,TopCentralProduct::getBatchNo,TopCentralProduct::getBatchNo));
    }

    /**
     * 获取产品详细信息
     */
    @RequiresPermissions("central:centralProduct:query")
    @GetMapping(value = "/{id}")
    @ResponseBody
    public AjaxResult getInfo(@PathVariable("id") Integer id)
    {
        return AjaxResult.success(topCentralProductService.selectById(id));
    }

    /**
     * 获取自增排序值
     * @param topCentralProduct 过滤条件
     * @return
     */
    @GetMapping("/getIncrementWeight")
    @ResponseBody
    public AjaxResult getIncrementWeight(TopCentralProduct topCentralProduct){
        int weigth = topCentralProductService.getMaxOfWeight(topCentralProduct);
        return AjaxResult.success(++weigth);
    }

    /**
     * 下载产品导入模板
     */
    @GetMapping("/importTemplate")
    @ResponseBody
    public void importTemplate(HttpServletResponse response)
    {
        ExcelUtil<TopCentralProduct> util = new ExcelUtil<>(TopCentralProduct.class);
        util.importTemplateExcel(response, "产品数据");
    }

    /**
     * 导入产品数据
     * @param file 产品数据文件
     * @param updateSupport 是否为更新
     */
    @Log(title = "产品", businessType = BusinessType.IMPORT)
    @RequiresPermissions("central:centralProduct:import")
    @PostMapping("/importData")
    @ResponseBody
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception
    {
        ExcelUtil<TopCentralProduct> util = new ExcelUtil<>(TopCentralProduct.class);
        List<TopCentralProduct> topCentralProductList = util.importExcel(file.getInputStream());

        if(updateSupport){
            if(topCentralProductService.updateBatchById(topCentralProductList)){
                return AjaxResult.success("导入产品数据覆盖成功！");
            }
            return AjaxResult.error("导入产品数据覆盖失败！");
        }
        if(topCentralProductService.insertBatch(topCentralProductList)){
            return AjaxResult.success("导入产品数据新增成功！");
        }
        return AjaxResult.error("导入产品数据新增失败！");
    }

    /**
     * 导出产品列表
     */
    @RequiresPermissions("central:centralProduct:export")
    @Log(title = "产品", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(TopCentralProduct topCentralProduct)
    {
        List<TopCentralProduct> list = topCentralProductService.selectList(topCentralProduct);
        ExcelUtil<TopCentralProduct> util = new ExcelUtil<TopCentralProduct>(TopCentralProduct.class);
        return util.exportExcel(list, "产品数据");
    }

    /**
     * 新增产品
     */
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

    /**
     * 新增保存产品
     */
    @RequiresPermissions("central:centralProduct:add")
    @Log(title = "产品", businessType = BusinessType.INSERT)
    @PostMapping
    @ResponseBody
    public AjaxResult addSave(@Validated(InsertGroup.class) @RequestBody TopCentralProduct topCentralProduct)
    {
        return toAjax(topCentralProductService.insert(topCentralProduct));
    }

    /**
     * 修改产品
     */
    @RequiresPermissions("central:centralProduct:edit")
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Integer id, ModelMap mmap)
    {
        TopCentralProduct topCentralProduct = topCentralProductService.selectById(id);
        mmap.put("topCentralProduct", topCentralProduct);
        return prefix + "/edit";
    }

    /**
     * 修改保存产品
     */
    @RequiresPermissions("central:centralProduct:edit")
    @Log(title = "产品", businessType = BusinessType.UPDATE)
    @PutMapping
    @ResponseBody
    public AjaxResult editSave(@Validated(UpdateGroup.class) @RequestBody TopCentralProduct topCentralProduct)
    {
        return toAjax(topCentralProductService.updateById(topCentralProduct));
    }

    /**
     * 修改产品 状态 根据 ids 主键
     */
    @RequiresPermissions("central:centralProduct:edit")
    @Log(title = "产品", businessType = BusinessType.UPDATE)
    @PutMapping("/updateStateByIds")
    @ResponseBody
    public AjaxResult updateStateByIds(@Validated(value= UpdateBatchGroup.class)@RequestBody StateVo<Integer> stateVo)
    {
        return toAjax(topCentralProductService.updateStateByIds(stateVo.getIds(),stateVo.getState()));
    }

    /**
     * 删除产品
     */
    @RequiresPermissions("central:centralProduct:remove")
    @Log(title = "产品", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    @ResponseBody
    public AjaxResult deleteByIds(@PathVariable("ids") List<Integer> ids)
    {
            return toAjax(topCentralProductService.deleteByIds(ids));
    }
}
